import 'package:background_downloader/background_downloader.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/XScaffold/XScaffold.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/components/ChatSessionWidget/components/MessageListWidget/components/DetailItemWidget/DetailItemWidget.dart';
import 'package:orginone/config/constant.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/model.dart' hide Column;
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/log/log_util.dart';

import '../../XButton/XButton.dart';

class FileDownloadWidget extends StatefulWidget {
  const FileDownloadWidget({super.key});

  @override
  State<FileDownloadWidget> createState() => _MessageFilePageState();
}

class _MessageFilePageState extends State<FileDownloadWidget> {
  late FileItemShare fileShare;

  late String type;

  var downloadStatus = DownloadStatus.notStarted.obs;

  var downloadProgress = 0.0.obs;

  DownloadTask? task;

  @override
  void initState() {
    fileShare = RoutePages.getPageParams;
    FileDownloader().database.allRecords().then((records) {
      try {
        if (records.isNotEmpty) {
          task = records
              .firstWhere((element) => element.task.filename == fileShare.name!)
              .task as DownloadTask;
          downloadStatus.value = task != null
              ? DownloadStatus.downloadCompleted
              : DownloadStatus.notStarted;
          downloadStatus.refresh();
        }
      } catch (e) {
        XLogUtil.e(e);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return XScaffold(
      body: Container(
          width: double.infinity,
          color: Colors.white,
          child: Flex(
            direction: Axis.vertical,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      height: 100.h,
                    ),
                    XImage.entityIcon(fileShare, width: 60.w),
                    // Icon(
                    //   Icons.file_open,
                    //   size: 60.w,
                    // ),
                    SizedBox(
                      height: 40.h,
                    ),
                    Container(
                      width: double.infinity,
                      margin: const EdgeInsets.only(left: 50, right: 50),
                      alignment: Alignment.center,
                      child: Text(
                        fileShare.name ?? "",
                        style: XFonts.size26Black0,
                      ),
                    ),
                    SizedBox(
                      height: 5.h,
                    ),
                    Container(
                      width: double.infinity,
                      margin: const EdgeInsets.only(left: 50, right: 50),
                      alignment: Alignment.center,
                      child: Text(
                        '文件大小：${getFileSizeString(bytes: fileShare.size ?? 0)}',
                        style: XFonts.size16Black9,
                      ),
                    ),
                  ]),
              Column(
                children: [
                  Obx(() {
                    if (downloadStatus.value == DownloadStatus.downloading) {
                      return Column(
                        children: [
                          Text(
                            "正在接收下载文件",
                            style: XFonts.size16Black9,
                          ),
                          SizedBox(
                            height: 10.h,
                          ),
                          CircularProgressIndicator(
                            value: downloadProgress.value,
                            backgroundColor: XColors.statisticsBoxColor,
                            valueColor: const AlwaysStoppedAnimation<Color>(
                                XColors.blueTextColor),
                          )
                        ],
                      );
                    }
                    // return GestureDetector(
                    //   onTap: () {
                    //     if (downloadStatus.value ==
                    //         DownloadStatus.downloadCompleted) {
                    //       openFile();
                    //     } else {
                    //       downloadFile();
                    //     }
                    //   },
                    //   child: Column(
                    //     children: [
                    //       Container(
                    //           width: 220.w,
                    //           height: 60.h,
                    //           decoration: BoxDecoration(
                    //             color: XColors.themeColor,
                    //             borderRadius: BorderRadius.circular(10.w),
                    //           ),
                    //           alignment: Alignment.center,
                    //           child: Text(
                    //             downloadStatus.value == DownloadStatus.downloadCompleted
                    //                 ? "打开"
                    //                 : "下载",
                    //             style: TextStyle(color: Colors.white, fontSize: 20.sp),
                    //           )),
                    //     ],
                    //   ),
                    // );
                    return XButton.solidMin(
                      downloadStatus.value == DownloadStatus.downloadCompleted
                          ? "打开"
                          : "下载",
                      padding: 100,
                      onPressed: () async {
                        if (downloadStatus.value ==
                            DownloadStatus.downloadCompleted) {
                          openFile();
                        } else {
                          downloadFile();
                        }
                      },
                    );
                  }),
                  SizedBox(
                    height: 200.h,
                  ),
                ],
              ),
            ],
          )),
    );
  }

  void downloadFile() async {
    task = DownloadTask(
        url: '${Constant.host}${fileShare.shareLink}',
        baseDirectory: BaseDirectory.applicationSupport,
        filename: fileShare.name!);
    ToastUtils.showMsg(msg: "开始下载");
    downloadStatus.value = DownloadStatus.downloading;
    await FileDownloader().download(task!, onProgress: (prpgress) {
      downloadProgress.value = prpgress;
      if (prpgress == 1) {
        FileDownloader().trackTasks();
        downloadStatus.value = DownloadStatus.downloadCompleted;
        ToastUtils.showMsg(msg: "下载完成");
      }
    });
  }

  void openFile() async {
    await FileDownloader().openFile(task: task);
  }
}

enum DownloadStatus {
  notStarted,
  downloading,
  downloadCompleted,
}
